//
//  RequestManager.m
//  HYTAPP
//
//  Created by 林建 on 17/7/24.
//  Copyright © 2017年 林建. All rights reserved.
//

#import "RequestManager.h"
#import<CommonCrypto/CommonDigest.h>
@implementation RequestManager
+(void)requestWithUrlStringForAFN:(NSString *)urlString parDic:(NSDictionary *)parDic requestType:(RequestType)requestType finish:(Finish)finish error:(Error)error{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager requestWithUrlStringForAFN:urlString parDic:parDic requestType:requestType finish:finish error:error];
}

-(void)requestWithUrlStringForAFN:(NSString *)urlString parDic:(NSDictionary *)parDic requestType:(RequestType)requestType finish:(Finish)finish error:(Error)error{
    self.finish = finish;
    self.error = error;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", @"charset=utf-8", nil];
    NSDate *dateObc = [NSDate date];
    NSString *Timestamp = [NSString stringWithFormat:@"%d",(int)[dateObc timeIntervalSince1970]];
    //    [NSString stringWithFormat:@"%d",(int)[dateObc timeIntervalSince1970]];
    // @"1512454752";
    NSData *dictData = [NSJSONSerialization dataWithJSONObject:parDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:dictData encoding:NSUTF8StringEncoding];
    NSString *Signature = [NSString stringWithFormat:@"%@%@%@%@",kAppId,Timestamp,kKey,jsonString];
    [manager.requestSerializer setValue:kAppId forHTTPHeaderField:@"appId"];
    [manager.requestSerializer setValue:[[SingleManager shareManager] md5:Signature] forHTTPHeaderField:@"signature"];
    [manager.requestSerializer setValue:Timestamp forHTTPHeaderField:@"timestamp"];
    
    if (requestType == RequestGET) {
        [manager POST:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.finish(responseObject);
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@" error");
        }];
    } else {
        [manager POST:urlString parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.finish) {
                    
                    self.finish(responseObject);
                }
            });
            NSLog(@"responseObject NSData");
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.error(error);
            NSLog(@"error");
        }];
    }
}

+(void)requestwithTokenUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{
    RequestManager *request = [[RequestManager alloc]init];
    [request requestwithTokenUrlString:urlString requestType:requestType parDic:parDic finish:finish error:error];
}

#pragma mark ----- 数据请求 -----
-(void)requestwithTokenUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;
{
    //对block属性进行赋值
    self.finish = finish;
    self.error = error;
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 60;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //如果是POST请求
    if (requestType == RequestPOST) {
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[self pardicToPOSTData:parDic]];
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            self.error(error);
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.finish(data);
            });
        }
    }];
    //调用此方法 才是去异步链接
    [task resume];
}

-(NSData *)pardicToPOSTData:(NSDictionary *)parDic
{
    NSData *dictData = [NSJSONSerialization dataWithJSONObject:parDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:dictData encoding:NSUTF8StringEncoding];
    return [jsonString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
